//
//  YpViewController.m
//  KIASupervisory
//
//  Created by apple on 15/7/19.
//  Copyright (c) 2015年 MyCompany. All rights reserved.
//

#import "BaoxViewController.h"
#import "TongzhiListViewController.h"
#import "MainViewController.h"
#import "SXDetailModel.h"
#import "SXDetailImgModel.h"
#import "SXHTTPManager.h"
#import "WeixListViewController.h"
#import "CameraAlbum.h"
#import "MTStatusBarOverlay.h"
#import "PhotoTableViewCell.h"
@interface BaoxViewController ()<UIActionSheetDelegate,UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,
CameraAlbumDelegate,PhotoTableCellDelegate>

@property (nonatomic, strong) NSMutableArray *ypList;
@property (nonatomic, strong) UIButton *back;
@property (nonatomic,strong) SXDetailModel *detailModel;
@property (nonatomic, strong) NetworkManager *networkManager;
@property (nonatomic, strong) MBProgressHUD *HUD;

@property (weak, nonatomic) IBOutlet UITextView *contentTv;
@property (weak, nonatomic) IBOutlet UITableView *pictureTable;
@property (weak, nonatomic) IBOutlet UITextField *baoxiuTitle;
@property (weak, nonatomic) IBOutlet UITextField *dizhiTitle;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (nonatomic, strong) CameraAlbum *cameraAlbum;
@property (nonatomic, strong) NSMutableArray *imageList;
@property (nonatomic, strong) UIAlertView *alertView;
@property (nonatomic, assign) CGRect contentPreFrame;

- (IBAction)takePhotoAction:(id)sender;

@end

@implementation BaoxViewController

@synthesize dataList = _dataList;
@synthesize showData = _showData;

- (void)viewDidLoad
{
    [self.navigationController setNavigationBarHidden:YES];
    self.networkManager = [[NetworkManager alloc] init];
    self.detailModel = [[SXDetailModel alloc] init];
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.delegate = self;
    [super viewDidLoad];
    self.imageList = [NSMutableArray array];
    
    [self transAppTableToHorizontal];
    CGRect frame = self.contentTv.frame;
    NSLog(@"*********pre frame:%@",NSStringFromCGRect(self.contentTv.frame));
       self.contentPreFrame = frame;

    //定义一个toolBar
    UIToolbar
    * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
    //设置style
    [topView
     setBarStyle:UIBarStyleBlack];
    //定义两个flexibleSpace的button，放在toolBar上，这样完成按钮就会在最右边
    
    UIBarButtonItem
    * button1 =[[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem
    * button2 = [[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    //定义完成按钮
    UIBarButtonItem
    * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成"style:UIBarButtonItemStyleDone
                                                  target:self action:@selector(resignKeyboard)];
    
    //在toolBar上加上这些按钮
    NSArray
    * buttonsArray = [NSArray arrayWithObjects:button1,button2,doneButton,nil];
    
    [topView
     setItems:buttonsArray];
    
    [self.baoxiuTitle setInputAccessoryView:topView];
    [self.dizhiTitle setInputAccessoryView:topView];
    [self.contentTv setInputAccessoryView:topView];
    
    
    
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
    
    CGRect frame = self.contentPreFrame;
    self.contentTv.frame = CGRectMake(frame.origin.x, frame.origin.y - 180,
                                      frame.size.width, frame.size.height);
    CGRect frame2 = self.label.frame;
    
    frame2.origin.y -= 180;
    
    self.label.frame = frame2;
    [UIView commitAnimations];
}

- (void)textViewDidChange:(UITextView *)textView{
    CGRect frame = self.contentPreFrame;
    if ([textView.text length] == 0) {
        [_label setHidden:NO];
    }else{
        [_label setHidden:YES];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    CGRect frame2 = self.label.frame;
    
    frame2.origin.y += 180;
    
    self.label.frame = frame2;
    if ([textView.text length] == 0) {
        [_label setHidden:NO];
    }else{
        [_label setHidden:YES];
    }
    
    self.contentTv.frame = self.contentPreFrame;
    
    [UIView commitAnimations];
    
}

-(void)resignKeyboard
{
    [self.baoxiuTitle resignFirstResponder];
    [self.dizhiTitle resignFirstResponder];
    [self.contentTv resignFirstResponder];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (IBAction)backToPre:(id)sender {
//    WeixListViewController *problemVC = (WeixListViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"WeixListViewController"];
//    CATransition* transition = [CATransition animation];
//    transition.type = kCATransitionPush;//可更改为其他方式
//    transition.subtype = kCATransitionFromRight;//可更改为其他方式
//    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
//    [self.navigationController pushViewController:problemVC animated:NO];
    [self.navigationController popViewControllerAnimated:YES];
}

//点击拍照按钮
- (IBAction)takePhotoAction:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照",@"从相册选择", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
    
    //    [self openSystemCamera];
}

-(IBAction)fabu:(id)sender{
    if (![self.baoxiuTitle hasText]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"标题不能为空，请填写之后再提交"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if (![self.dizhiTitle hasText]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"报修地址不能为空，请填写之后再提交"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else {
        if ([self.contentTv hasText]) {
            if ([self.imageList count] >3 ) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"照片超过3张，请确认后提交"
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            } else {
                [self.HUD show:YES];
                [self performSelectorInBackground:@selector(submitIssueReuqest) withObject:nil];
            }
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"问题描述不能为空，请填写之后再提交"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }
}


- (void)submitIssueReuqest {
    
    
    NSString *wtms = self.contentTv.text; //问题描述
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    long interval = (long)timeInterval;
    
    UserInfo *user = [UserInfo instance];
    NSLog(@"@@@@@@user_id====%@",[user.info objectForKey:@"user_id"]);
    NSLog(@"@@@@@@xiaoqu_id====%@",[user.info objectForKey:@"xiaoqu_id"]);
    NSString *xiaoqu_id = [user.info objectForKey:@"xiaoqu_id"];
    NSString *user_id =[user.info objectForKey:@"user_id"];
    NSString *wtpc = [NSString stringWithFormat:@"%ld",interval];
    NSString *path = [NSString stringWithFormat:@"%@",wtpc];
    NSLog(@"*******path:%@",path);
    
    NSMutableArray *fileList = [NSMutableArray array];
    NSMutableArray *fileNameList = [NSMutableArray array];
    if ([self.imageList count] > 0) {
        
        for (int i = 0; i < [self.imageList count]; i ++) {
            UIImage *image = (UIImage *)[self.imageList objectAtIndex:i];
            NSData *imgData = nil;
            NSString *imagetype = @".jpeg";
            if (image != nil) {
                if (UIImagePNGRepresentation(image) == nil) {
                    imgData = UIImageJPEGRepresentation(image, 1);
                    imagetype = @".jpeg";
                } else {
                    imgData = UIImagePNGRepresentation(image);
                    imagetype = @".png";
                }
            }
            
           NSString *fileName = [NSString stringWithFormat:@"%@/%d%@",path,i+1,imagetype];
            [fileNameList addObject:fileName];
            NSDictionary *fileDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                      imgData,@"path",
                                      fileName,@"name", nil];
            [fileList addObject:fileDict];
        }
    }
    
   NSString *fileNameListStr = [fileNameList componentsJoinedByString:@","];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           fileList,@"FILE",
                           fileNameListStr,@"fileList",
                           user_id,@"user_id",
                           self.baoxiuTitle.text ,@"title",
                           self.dizhiTitle.text ,@"weiz",
                           xiaoqu_id,@"xiaoqu_id",
                           wtms,@"content",
                           path,@"md_input_path", nil];
    [self.networkManager requestWithMethod:createWeixiu parameter:param delegate:self];
}

#pragma mark - Camera
- (void)openSystemCamera{
    if (self.cameraAlbum==nil) {
        self.cameraAlbum = [CameraAlbum instance];
        self.cameraAlbum.delegate = self;
    }
    
    [self.cameraAlbum openCameraInTargetViewController:self];
}

- (void)openSystemImageLib{
    if (self.cameraAlbum==nil) {
        self.cameraAlbum = [CameraAlbum instance];
        self.cameraAlbum.delegate = self;
    }
    [self.cameraAlbum openPhotoLibraryInTargetViewController:self];
}

#pragma mark - CameraAlbumDelegate
//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this newcontext, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

- (UIImage *)setTheSeletedImage:(UIImage *)image
{//压缩图片
    UIImage *returnImage = [[UIImage alloc]init];
    //h=720, w=640
    if (image.size.height > image.size.width) {
        if (image.size.height < 640) {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)];
        }else{
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width*640/image.size.height, 640)];
        }
        
    } else {
        if (image.size.width < 640) {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)];
        }else {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(640, image.size.height*640/image.size.width)];
        }
    }
    return returnImage;
    //压缩后图片
}

-(void)getSavedImage:(UIImage*)image {
    UIImage *selectedImage = [self setTheSeletedImage:image];
    if (self.imageList == nil) {
        self.imageList = [NSMutableArray array];
    }
    if (selectedImage != nil) {
        [self.imageList addObject:selectedImage];
    }
    [self.pictureTable reloadData];
}

- (void)transAppTableToHorizontal {
    CGRect frame = self.pictureTable.frame;
    
    self.pictureTable.showsVerticalScrollIndicator = NO;
    self.pictureTable.showsHorizontalScrollIndicator = NO;
    self.pictureTable.transform = CGAffineTransformMakeRotation(-M_PI * 0.5);
    self.pictureTable.frame = frame;
    self.pictureTable.clipsToBounds = NO;
    self.pictureTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.pictureTable.separatorColor = [UIColor clearColor];
    self.pictureTable.dataSource = self;
    self.pictureTable.delegate = self;
    self.pictureTable.pagingEnabled = YES;
    
}

- (void)clearViewContent {
    self.contentTv.text = @"";
    
    [self.imageList removeAllObjects];
    [self.pictureTable reloadData];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [self openSystemCamera];
    }
    else if (buttonIndex==1) {
        [self openSystemImageLib];
    }
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    //[self endRefresh];
    //self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"数据获取失败，请稍后重试";
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}


#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.imageList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"identifier";
    PhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[PhotoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        [cell setBackgroundColor:[UIColor clearColor]];
        cell.delegate = self;
    }
    
    int row = indexPath.row;
    if ([self.imageList count] > row) {
        UIImage *image = [self.imageList objectAtIndex:row];
        [cell updateDatas:image atIndex:indexPath];
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 70.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - PhotoTableViewCellDelegate
- (void)willDeleteItem:(PhotoItemView *)item inCell:(PhotoTableViewCell *)cell {
    NSIndexPath *indexPath = cell.indexPath;
    NSInteger row = indexPath.row;
    if (0 <= row && [self.imageList count] > row) {
        [self.imageList removeObjectAtIndex:row];
    }
    [self.pictureTable reloadData];
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    
    if (methodId == createWeixiu) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            if ([data isKindOfClass:[NSDictionary class]]) {
                NSString * result = [data objectForKeyOrNil:@"result"];
                NSLog(@"@@@@@@@@@@@@@@@@state%@",result);
                NSString *msg = @"";
                if([result isEqualToString:@"000"]){
                    msg = @"报修提交成功";
                    [self showAlertViewWithMessage:msg];
                    WeixListViewController *problemVC = (WeixListViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"WeixListViewController"];
                    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:problemVC];
                    DDMenuController *menuVC = [[DDMenuController alloc] initWithRootViewController:navController];
//                    [self presentViewController:menuVC animated:YES completion:^{}];
                    [self.navigationController pushViewController:menuVC animated:YES];
                } else {
                    msg = @"报修提交失败";
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:msg
                                                                   delegate:nil
                                                          cancelButtonTitle:@"确定"
                                                          otherButtonTitles:nil];
                    [alert show];
                }
                
            }
        }
    }
}


- (void)showAlertViewWithMessage:(NSString *)msg {
    if ([msg length] > 0) {
        _alertView = [[UIAlertView alloc] initWithTitle:@""
                                                message:msg
                                               delegate:self
                                      cancelButtonTitle:@"确定"
                                      otherButtonTitles:nil];
        _alertView.tag = 10001;
        [NSTimer scheduledTimerWithTimeInterval:0.9f
                                         target:self
                                       selector:@selector(performDismissAlert)
                                       userInfo:nil
                                        repeats:NO];
        [_alertView show];
    }
}

- (void)performDismissAlert {
    if (_alertView) {
        [_alertView dismissWithClickedButtonIndex:0 animated:NO];
        _alertView = nil;
    }
}

@end

